﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Vaffanculo.Data.Interfaces;
using Vaffanculo.Data.Implements;

namespace Vaffanculo.Service.Infrastructure
{
    /// <summary>
    /// Class help for execute operations in transactions
    /// </summary>
    public class BaseService
    {
        /// <summary>
        /// Method for execute transactions
        /// </summary>
        /// <param name="coreMethod">Method anonymous that execute operations into transaction</param>
        /// <param name="postCommit">Method anonymous that should execute after ending operations in transaction</param>
        public void ExecuteManager(Action<IUnitOfWork> coreMethod, Action postCommit = null)
        {
            // Object context definition to specific model/database
            DbContextVaffanculo contextVaffanculo = new DbContextVaffanculo();

            IDbContext context = new DbContextAdap(contextVaffanculo);

            IUnitOfWork uow = new UnitOfWork(context);
            bool success = false;

            try
            {
                coreMethod(uow);
                success = true;
            }
            catch (Exception ex)
            {
                Console.WriteLine("An error occured. "
                        + "The operation cannot be retried."
                        + ex.Message);

            }

            if (success)
            {
                // Save all changes.
                uow.Commit();
                // Execute anonymous method after commit if exists
                if (postCommit != null)
                {
                    postCommit();
                }
            }
            else
            {
                Console.WriteLine("The operation could not be completed");

            }
            // Dispose connection
            uow.GetIDbContext().Dispose();            
        }
    }
}
